package properties

import (
	"encoding/json"
	"errors"
	"fmt"
	"gitee.com/kristas/booting-go/framework/common/util/convert"
	"gitee.com/kristas/booting-go/framework/common/util/lang"
)

func Unmarshal(data []byte, v interface{}) error {
	properties := lang.NewString(string(data)).Trims().Split("\n")
	pm := make(map[string]interface{})
	for i, property := range properties {
		kv := property.SplitN("=", 2)
		if len(kv) != 2 {
			return errors.New(fmt.Sprintf("invalid property: %s at line %d", property.String(), i+1))
		}
		key := kv[0].Trim(" ").String()
		if kv[1].Contains(",") {
			arr := kv[1].Split(",")
			slices := make([]interface{}, 0)
			for _, s := range arr {
				inference, err := convert.Inference(s.Trim(" ").String())
				if err != nil {
					return err
				}
				slices = append(slices, inference)
			}
			pm[key] = slices
		} else {
			inference, err := convert.Inference(kv[1].Trim(" ").String())
			if err != nil {
				return err
			}
			pm[key] = inference
		}
	}
	toMap := PropMapExpand(pm)
	jsonBytes, err := json.Marshal(toMap)
	if err != nil {
		return err
	}
	return json.Unmarshal(jsonBytes, v)
}
